import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { FeeEnquiryService } from 'src/app/service/fee-enquiry/fee-enquiry.service';
import { NoteOrderService } from 'src/app/service/me/note-order.service';
import { MessageService } from 'src/app/service/message.service';
import { UserBindService } from 'src/app/service/user-bind.service';
import { UserInfoService } from 'src/app/service/user-info/user-info.service';

@Component({
  selector: 'app-note-order',
  templateUrl: './note-order.component.html',
  styleUrls: ['./note-order.component.scss']
})
export class NoteOrderComponent implements OnInit {

  constructor(
    private userInfo: UserInfoService,
    private router: Router,
    private feeEnquiryService: FeeEnquiryService,
    private message: MessageService,
    private noteOrderService: NoteOrderService,
    private http: HttpClient,
    private route: ActivatedRoute,
    private userBind: UserBindService
  ) { }

  ngOnInit() {
    this.route.queryParams.subscribe((res: any) => {
      if(res.isOrder === 'true' && this.noteOrderService.formData){
        this.pageType = 1
        this.validateForm.disable()
      }else{
        this.pageType = 0
      }
      this._isLogin();
      this.pageInit()
    })
  }

  userTel = ''
  _isLogin(){
    const userInfo: any = this.userInfo.getUserInfo()
    
    if(!userInfo || userInfo === null ){
      this.router.navigate(['/login'])
      return
    }
    this.userTel = userInfo.phone

    return ;
  }
  pageType = 0
  //#region 新的信息定制
  pageInit(){
    this._getBindList()
  }

  // {
  //   "setId": "99403df4-9647-4df1-83dd-2fed95376c6b",
  //   "typeId": "194abfce-5ccd-4b47-913a-72f9a7af7ab9",
  //   "infoSources": "WT",
  //   "msgWay": "0dc1cc45-7a35-4241-888c-9f392a5e2f17",
  //   "address": "一德************1",
  //   "usageCode": "0009575325",
  //   "userNo": "{\"accountName\":\"\",\"usageCode\":\"0009575325\",\"address\":\"一德************1\",\"meterNo\":\"\",\"meterAddr\":\"\"}",
  //   "phone": "15736873782"
  // }
  validateForm = new FormGroup({
    usageCode: new FormControl('', [
      Validators.required
    ]),
    phone: new FormControl('', [
      // Validators.required,
      // Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)
    ]),
    username: new FormControl(''),
    ywkt: new FormControl('0'),
    // mesType: new FormControl([] as any),

    address: new FormControl(''),
    setId: new FormControl('99403df4-9647-4df1-83dd-2fed95376c6b'),
    typeId: new FormControl('194abfce-5ccd-4b47-913a-72f9a7af7ab9'),
    infoSources: new FormControl('WT'),
    msgWay: new FormControl('0dc1cc45-7a35-4241-888c-9f392a5e2f17'),
    isSecret: new FormControl(true)
  });
  usageCodeLoading = false
  onUsageCodeChange(e: string){
    const item: any = this.userBindList.find((_: any) => _.usageCode === e)
    console.log(item)
    if(item){
      this.validateForm.patchValue({
        address: item.address
      })
      if(this.pageType === 0){
        // this._getUserOrder()
      }
    }
  }
  onMesTypeChange(e: any){
    console.log(e)
  }

  userBindList: any = []
  _getBindList() {
    this.usageCodeLoading = true
    this.userBind._getBindList().subscribe(res => {
      console.log(res)
      this.userBindList = res;
      
      const formData = this.noteOrderService.formData ? JSON.parse(this.noteOrderService.formData) : null
      if(this.pageType === 1){
        this.validateForm.patchValue({ 
          usageCode: formData.usageCode, 
          address: formData.address,
          phone: formData.phone,
          username: formData.name
          // mesType: formData.mesType ? formData.mesType.split(',').map((_: any) => _.substr(0, _.indexOf(":"))) : []
        })
        console.log(formData.mesType.split(',').map((_: any) => _.substr(0, _.indexOf(":"))))
      }else{
        this.validateForm.patchValue({ 
          usageCode: res[0].usageCode, 
          address: res[0].address,
          phone: this.userTel,
          username: res[0].name
        })
      }
      // this._getCustDetails()
      this.usageCodeLoading = false;
    }, error => {
      this.usageCodeLoading = false;
      this.message.info('查询用户编号信息失败');
    })
  }

  // 按钮相关
  btnLoading = false
  onSubmit(){
    // .get('mesType')?.value?.length
    // if((this.validateForm.get('mesType')?.value?.length) as any <= 0){
    //   this.message.confirmModal('未选择相关业务, 确认不开通所有业务吗', () => {
    //     this.submit()
    //   })
    //   return
    // }
    this.submit()
  }
  submit(){
    let controls = this.validateForm.controls;
    for (let i in controls) {
      controls[i].markAsDirty();
      controls[i].updateValueAndValidity();
    }

    for (let i in controls) {
      if (controls[i].invalid) {
        console.log(controls[i])
        return;
      }
    }

    const url = '/api/gsxmcp/cf/mg/v1.0/funcData'
    const params: any = this.validateForm.getRawValue()
    // params.mesType = params.mesType.map((item: any) => {
    //   const t: any = this.userOrders.find((_: any) => _.id === item)
    //   if(t){
    //     return `${t.id}:${t.type}`
    //   }else{
    //     return `${item}:null`
    //   }
    // })
    // params.mesType = params.mesType.join(',')

    params.userNo = `{\"usageCode\":\"${this.usageCode}\",\"address\":\"${this.validateForm.get('address')?.value}\"}`


    this.btnLoading = true
    this.http.post(url, params).subscribe(res => {
      this.message.success('提交成功')
      this.btnLoading = false
    }, error => {
      this.message.createErrorMessage(error)
      this.btnLoading = false
    })
  }
  onReset(){
    this.message.confirmModal('确认初始化表单吗？', () => {
      this.validateForm.patchValue({
        usageCode: this.userBindList[0]?.usageCode,
        address: this.userBindList[0].address,
        // mesType: this.userOrders.map((_: any) => _.id)
      })
    })
  }
  

  // 信息定制列表
  mesNzLoading = false;
  listOfOption: Array<{ label: string; value: string }> = [];
  visibleList = ['暂收水费通知', '欠缴费用通知', '抄表预约通知', '当期水费通知', '当期水费到期通知']
  _getCustDetails() {
    this.mesNzLoading = true;
    this.noteOrderService.getCustDetails().subscribe(res => {
      if (res) {
        // console.log(res);
        let children: Array<{ label: string; value: string }> = [];
        res.forEach((item: any) => {
          if(this.visibleList.indexOf(item.typeName) > -1){
            children.push({ label: item.typeName, value: item.id });
          }
        })
        this.listOfOption = children;
        // console.log(this.listOfOption);
        // if(this.pageType === 0){
        //   this._getUserOrder()
        //   return
        // }
        this.mesNzLoading = false;
      }else{
        this.message.error('查询可开通业务失败');
      }
      // this.mesNzLoading = false;
    }, error => {
      this.mesNzLoading = false;
      this.message.createErrorMessage(error);
    })
  }
  // 获取用户订阅的业务列表
  userOrders = []
  _getUserOrder(){
    this.userOrders = []
    const url = `/api/gsxmcp/ot/ms/v1.0/mesCust/${this.usageCode}/${this.userTel}`
    // const url = '/api/gsxmcp/ot/ms/v1.0/mesCust/0000000013/15822223333'
    this.http.get(url).subscribe((res: any) => {
      console.log(res)
      if(res && res.length > 0){
        this.userOrders = res
        const temp = res.map((_: any) => _.id)
        // this.validateForm.patchValue({
        //   mesType: temp
        // })
      }else{
        // this.validateForm.patchValue({
        //   mesType: []
        // })
      }
      this.mesNzLoading = false
    }, error => {
      this.message.createErrorMessage(error)
      this.mesNzLoading = false
    })
  }

  get usageCode(){
    return this.validateForm.get('usageCode')?.value
  }
  //#endregion

}
